package me.stone.stanimeclient.page.catalog

import androidx.paging.PagingSource
import androidx.paging.PagingState
import me.stone.stanimeclient.core.data.domain.data.LoadCatalogListRepository
import me.stone.stanimeclient.core.model.FanIntroItem
import timber.log.Timber

class CatalogPagingSource(
    private val repository: LoadCatalogListRepository,
    private val queryParam: Map<String, String>
) : PagingSource<Int, FanIntroItem>() {

    override fun getRefreshKey(state: PagingState<Int, FanIntroItem>): Int? {
        // 无法通过 id / position 获取当前页码
        // 当前查询条件失效后直接显示第一页
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, FanIntroItem> {
        val page = params.key ?: 1
        val pageSize = params.loadSize
        return try {
            val data = repository.loadCatalogList(page, queryParam, params.loadSize)
            val next = if (data.totalPage > page) page + 1 else null
            val prev = if (page > 1) page - 1 else null
            LoadResult.Page(
                data = data.data,
                prevKey = prev,
                nextKey = next
            )
        } catch (e: Exception) {
            Timber.d("error: $e")
            LoadResult.Error(e)
        }
    }

}